const Service = require("egg").Service;

class UserStudyDayService extends Service {
  // 记录用户学习天数
  async recordStudyDay(userId) {
    const { ctx } = this;
    const today = new Date().toISOString().split("T")[0]; // 获取当前日期（YYYY-MM-DD）
    const { word_count } = ctx.request.body;
    // 检查是否已经记录过今天的学习
    const existingRecord = await ctx.model.UserStudyDay.findOne({
      where: {
        user_id: userId,
        study_date: today,
      },
    });

    if (existingRecord) {
      await existingRecord.update({
        word_count: word_count,
      });
      return { message: "今天的学习已记录" };
    }

    // 创建新的学习记录
    const result = await ctx.model.UserStudyDay.create({
      user_id: userId,
      study_date: today,
      word_count: word_count,
    });

    return result;
  }

  // 获取用户的学习日期
  async getStudyDays(userId) {
    const { ctx } = this;
    const studyDays = await ctx.model.UserStudyDay.findAll({
      where: {
        user_id: userId,
      },
      attributes: ["study_date", "word_count"], 
      order: [["study_date", "ASC"]], // 按日期升序排列
    });

    return studyDays;
  }

  // 连续学习天数
  async getContinuousStudyDays(userId) {
    const { ctx } = this;

    const studyDays = await ctx.model.UserStudyDay.findAll({
      where: {
        user_id: userId,
      },
      attributes: ["study_date"],
      order: [["study_date", "DESC"]], // 按日期降序排列
    });

    let continuousDays = 0;
    let previousDate = null;

    for (const record of studyDays) {
      const currentDate = new Date(record.study_date);
      if (!previousDate) {
        previousDate = currentDate;
        continuousDays = 1;
        continue;
      }

      const diffTime = previousDate - currentDate;
      const diffDays = diffTime / (1000 * 60 * 60 * 24);

      if (diffDays === 1) {
        continuousDays++;
        previousDate = currentDate;
      } else {
        break;
      }
    }

    return continuousDays;
  }

  // 总学习天数
  async getTotalStudyDays(userId) {
    const { ctx } = this;
    const count = await ctx.model.UserStudyDay.count({
      where: {
        user_id: userId,
      },
    });
    return count;
  }
}

module.exports = UserStudyDayService;
